package com.lsh.oms.worker.service.task;

import com.dangdang.ddframe.job.api.JobExecutionMultipleShardingContext;
import com.dangdang.ddframe.job.plugin.job.type.simple.AbstractSimpleElasticJob;
import com.lsh.base.common.model.CommonResult;
import com.lsh.base.http.client.core.HttpClient;
import com.lsh.base.lang.Exceptions;
import com.lsh.base.lang.Maps;
import com.lsh.base.lang.json.Jsons;
import com.lsh.base.trace.id.filter.TraceIdSetter;
import com.lsh.oms.core.proxy.service.OfcProxy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;

import static com.lsh.base.lang.bean.Beans.*;

@Component
public class PullReturnStatusJob extends AbstractSimpleElasticJob {

    private static Logger LOGGER = LoggerFactory.getLogger(PullReturnStatusJob.class);

    @Value("${oms.host}")
    private String omsHost;

    @Value("${oms.base.path}")
    private String omsBasePath;

    @Resource
    private HttpClient https;

    @Resource
    private OfcProxy ofc;

    @Override
    public void process(JobExecutionMultipleShardingContext context) {
        String traceId = TraceIdSetter.set();
        Map<String, Object> response = https.get(basePath() + "/returns", Maps.newHashMap("status", "CHECKED", "return-required", true, "page", "1", "page-limit", "50"));
        Optional.ofNullable(getList(response, "data.entries"))
                .ifPresent(entries -> entries.forEach(entry -> {
                    Long id = getLong(entry, "id");
                    try {
                        CommonResult<Object> result = ofc.queryRoStatus(id);
                        LOGGER.info("pull return: {}, response: {}", id, Jsons.toJsonString(result));
                        Integer status = getInt(result.getData(), "status");
                        LOGGER.info("pull return: {}, status: {}", id, status);
                        if (isCompleted(status)) {
                            https.post(basePath() + "/returns/" + id + "/return",
                                    Maps.newHashMap("venderId", getString(entry, "vender_id"), "X-Local-Trace-Id", traceId),
                                    Collections.emptyMap());
                        }
                    } catch (Exception e) {
                        LOGGER.error("exception on return: {}", id);
                        Exceptions.printStackTraceLineByLine(e);
                    }
                }));
    }

    private boolean isCompleted(Integer status) {
        return Integer.valueOf(30).equals(status);
    }

    private String basePath() {
        return omsHost + omsBasePath;
    }
}
